package logic

import (
	"context"
	"net/http"
	"path/filepath"
	"time"
	"zgyzk3/pkg"

	"zgyzk3/zgyzk3api/internal/svc"
	"zgyzk3/zgyzk3api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	file, m, err := req.FormFile("img")

	if err != nil {
		return nil, err
	}
	Ext := filepath.Ext(m.Filename)
	if m.Size > 2*1024*1024 {
		return &types.Response{
			Message: "文件不能超过2M大小",
			Code:    "500",
			Data:    nil,
		}, nil
	}

	if Ext != ".png" && Ext != ".jpg" {
		return &types.Response{
			Message: "文件必须是jpg和png格式",
			Code:    "500",
			Data:    nil,
		}, nil
	}

	source := req.Form.Get("source")
	filename := source + "/" + time.Now().Format(time.DateTime) + Ext
	upload, err := pkg.Qny(file, m, filename)

	if err != nil {
		return &types.Response{
			Message: "",
			Code:    "500",
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Message: "",
		Code:    "200",
		Data:    upload,
	}, nil

}
